//
//  ZYCMessageTitleButton.m
//  ZDSC
//
//  Created by ZDTX on 2021/7/16.
//

#import "ZYCMessageTitleButton.h"
#import "ZYCAttributeStringHelpers.h"

@implementation ZYCMessageTitleButton

-(instancetype) initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        NSString *title = @"消息";
        CGSize size = [title sizeWithAttributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:23.f]}];
        self.frame = CGRectMake(0, 0, size.width, 20);
        [self setTitle:title forState:UIControlStateNormal];
        [self setTitleColor:HEX_RGB(@"#2B302D") forState:UIControlStateNormal];
        self.titleLabel.font = kSystemBoldFont(23.0f);
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateBadgeNum:) name:ZYCUnRedMessageCountNotification object:nil];
    }
    return self;
}

- (void)updateBadgeNum:(NSNotification *)noti{
    NSInteger totalCount = [noti.userInfo[@"totalCount"] integerValue];
    NSString *title = nil;
    if (totalCount > 100) {
        title = @"99+";
    }else if(totalCount == 0){
        title = @"";
    }else{
        title = [NSString stringWithFormat:@"%zd",totalCount];
    }

    [self setAttributedTitle:[self returnStringWithString:title] forState:UIControlStateNormal];
    CGSize titleSize = [[self returnStringWithString:title] size];
    self.frame = CGRectMake(0, 0, titleSize.width + 40, 20);
    [self setTitle:title forState:UIControlStateNormal];
}

- (NSMutableAttributedString *)returnStringWithString:(NSString *)string{
    if (string.length != 0){
        NSMutableAttributedString *fullStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"消息(%@)",string]];
        NSRange titleRange = [[NSString stringWithFormat:@"消息(%@)",string] rangeOfString:[NSString stringWithFormat:@"(%@)",string]];
        [fullStr addAttributes:@{NSFontAttributeName:kSystemFont(16.0f)} range:titleRange];
        return fullStr;
    }else{
        return [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"消息"]];
    }
    
}






@end
